
//Copyright 1997-2009 Syrinx Development, Inc.
//This file is part of the Syrinx Web Application Framework (SWAF).
// == BEGIN LICENSE ==
//
// Licensed under the terms of any of the following licenses at your
// choice:
//
//  - GNU General Public License Version 3 or later (the "GPL")
//    http://www.gnu.org/licenses/gpl.html
//
//  - GNU Lesser General Public License Version 3 or later (the "LGPL")
//    http://www.gnu.org/licenses/lgpl.html
//
//  - Mozilla Public License Version 1.1 or later (the "MPL")
//    http://www.mozilla.org/MPL/MPL-1.1.html
//
// == END LICENSE ==
using System;
using System.Collections.Generic;
using System.Text;

using Swaf;
using Swaf.BizObj;
using Swaf.Container;
using Swaf.Security;
using Swaf.Gui;

namespace Syrinx.Gui
{
    public delegate void CalendarEventHandler(IBusinessProcess bizProc, DateTime dateSelected);

    public class CalendarViewBizProc : BaseBusinessProcess
    {
        protected IBizObjListCalendarDisplay[] m_calendarDisplays;
        protected CalendarView m_currentView = CalendarView.Month;
        protected IBizObj m_calTemplate;
        protected IBizObjList m_baseCalData = null;

		public CalendarViewBizProc(ActiveBizProc procState)
			: base(procState)
		{
		}

        public void selectDate(DateTime dateSelected)
        {
			string calTemplateName = State.State.get("calendarTemplate") as string;
			m_calTemplate = App.appData.get("Calendars." + calTemplateName) as IBizObj;
			if (m_calTemplate == null)
                return;
			List<IBizObjListCalendarDisplay> listDisplays = getListDisplays();
			foreach (IBizObjListCalendarDisplay disp in listDisplays)
				if (!disp.IsInFlow)
                    disp.SelectedDate = dateSelected;
        }

		protected override void setupRuleNames()
		{
			
		}

		protected override Privileges CurrentEditPrivilege
		{
			get { return Privileges.Delete; }
		}
        

        protected void moveNext()
        {
			foreach (IBizObjListCalendarDisplay disp in getListDisplays())
                if (disp.IsInFlow)
                    disp.moveNext();
        }

        protected void movePrev()
        {
			foreach (IBizObjListCalendarDisplay disp in getListDisplays())
                if (disp.IsInFlow)
                    disp.movePrev();
        }

        protected void moveToday()
        {
			foreach (IBizObjListCalendarDisplay disp in getListDisplays())
                disp.FromDate = DateTime.Now;
        }

        protected void updatePartnerData()
        {
        }

        protected void addItem(object itemType)
        {
        }

        protected void switchFixedView(object viewName)
        {
            GenericAction swAction = Actions["SwitchFixed"] as GenericAction;
            swAction.CurrentParameterOption = viewName;
            CalendarView view = (CalendarView)Enum.Parse(typeof(CalendarView), viewName.ToString(), true);
			List<IBizObjListCalendarDisplay> listDisplays = getListDisplays();
			foreach (IBizObjListCalendarDisplay disp in listDisplays)
				if (!disp.IsInFlow)
                    disp.setCalendarFormat(view);
        }

        protected override void setupActions()
        {
			Actions.addAction(new GenericAction("MoveNext", true, moveNext, this));
			Actions.addAction(new GenericAction("MovePrev", true, movePrev, this));
			Actions.addAction(new GenericAction("MoveToday", true, moveToday, this));
			Actions.addAction(new GenericAction("Update", true, updatePartnerData, this));
            Actions.addAction(new GenericAction("AddItem", true, false, (ActionParamTrigger)addItem));
            GenericAction swAction = new GenericAction("SwitchFixed", true, false, switchFixedView, "Day", "Week", "Month");
            swAction.ShortName = "Calendar:";
            swAction.CurrentParameterOption = "Week";
            Actions.addAction(swAction);
            //Actions.addAction(new GenericAction("AddPartnerItem", false, addPartnerItem));
            //Actions.addAction(new GenericAction("DeletePartnerItem", false, deletePartnerItem));
            //Actions.addAction(new GenericAction("UpdatePartnerItem", false, updatePartnerItem));
        }

        #region IBizProcess Members
        public override void updateActionState()
        {
        }

        //public void useData(IBizObj calTemplate, IBizObjList calendarData)
		public override void  showData(ForceLevel level)
		{
			string calTemplateName = State.State.get("calendarTemplate") as string;
			m_calTemplate = App.appData.get("Calendars." + calTemplateName) as IBizObj;
			if (m_calTemplate != null)
			{
				FlexiMap dates = new FlexiMap();
				DateTime firstDate = DateTime.MaxValue, lastDate = DateTime.MinValue;
				List<IBizObjListCalendarDisplay> listDisplays = getListDisplays();
				foreach (IBizObjListCalendarDisplay disp in listDisplays)
				{
					disp.clearCalData();

					if (disp.IsInFlow)
					{
						if (lastDate != DateTime.MinValue)
							disp.FromDate = lastDate + new TimeSpan(1, 0, 0, 0);
						DateTime[] range = disp.calcRange();
						if (range[0] < firstDate)
							firstDate = range[0];
						if (range[1] > lastDate)
							lastDate = range[1];
					}
				}

				IBizObj currentView = m_calTemplate.get("views." + m_currentView.ToString()) as IBizObj;
				if (currentView != null)
				{
					dates["firstDate"] = firstDate;
					dates["lastDate"] = lastDate + new TimeSpan(1, 0, 0, 0);
					foreach (IBizObj partner in (IBizObjList)currentView.get("partners"))
					{
						IBizObjList partnerData = null;
						string ruleName = partner.get("getBizRule").ToString();
						if (!(ruleName == null || ruleName == ""))
						{
							IResults rc = App.ruleMgr.execute(ruleName, dates);
							partnerData = rc.CallResults as IBizObjList;
						}
						if (partnerData != null)
						{
							foreach (IBizObjListCalendarDisplay disp in listDisplays)
								if (disp.CalendarFormat == m_currentView && disp.IsInFlow)
									disp.addBizObjList(partner, partnerData);
						}
					}
				}

				foreach (IBizObjListCalendarDisplay disp in listDisplays)
				{
					if (!disp.IsInFlow)
					{
						currentView = m_calTemplate.get("views." + disp.CalendarFormat.ToString()) as IBizObj;
						if (currentView != null)
						{
							DateTime[] range = disp.calcRange();
							dates["firstDate"] = range[0];
							dates["lastDate"] = range[1] + new TimeSpan(1, 0, 0, 0);


							foreach (IBizObj partner in (IBizObjList)currentView.get("partners"))
							{
								IBizObjList partnerData = null;
								string ruleName = partner.get("getBizRule").ToString();
								if (!(ruleName == null || ruleName == ""))
								{
									IResults rc = App.ruleMgr.execute(ruleName, dates);
									partnerData = rc.CallResults as IBizObjList;
								}
								if (partnerData != null)
									disp.addBizObjList(partner, partnerData);
							}
						}
					}
				}
			}

        }

		public List<IBizObjListCalendarDisplay> getListDisplays()
		{
			List<IBizObjListCalendarDisplay> lists = new List<IBizObjListCalendarDisplay>();
			List<string> keys = m_procState.OfflineWidgetKeys;
			WidgetOfflineState wstate = null;
			foreach (string k in keys)
				if (m_procState.BPC.PageState.WidgetStates.TryGetValue(k, out wstate))
					foreach (string parentId in wstate.ParentBizProcIds)
						if (wstate.BizProcWidgetType == BizProcWidgetType.list && m_procState.OfflineState.Id.CompareTo(parentId) == 0)
							lists.Add(m_procState.BPC.getActiveWidget(wstate.Id).Widget as IBizObjListCalendarDisplay);
			return lists;
		}
		
		public event BPException BizProcException;

        #endregion
    }
}
